import json

from flask import Blueprint, jsonify
from flask import abort
from flask import current_app
from flask import request

from ihome_tenancy import redis_store
from ihome_tenancy.models import Area, Facility, House
from ihome_tenancy.utils.response_code import RET, ret_map

house_blueprint = Blueprint('house',__name__)


@house_blueprint.route('/house_detail', methods=['GET', 'POST'])
def house_detail():
    # - 1, 根据房屋编号获取房屋对象\
    house_id =  request.data('house_id')
    try:
        house_list = House.query.filter(House.id == house_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="房屋获取失败")
    # - 2, 判断是否存在
    if not house_list:
        abort(404)

    # - 3, 将房屋对象, 转成字典数据

    # - 4, 携带数据, 渲染页面
    return jsonify(errno=RET.OK,errmsg="数据返回成功",house=house_list.to_dict())


def area_get():
    area_list = redis_store.get('area_list')

    if not area_list:
        try:
            areas = Area.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DATAERR, msg=ret_map[RET.DATAERR])

        area_list = [area.to_dict() for area in areas]

        redis_store.set('area_list', json.dumps(area_list))
    else:
        area_list = json.loads(area_list)
    return area_list

def facility_get():
    facility_list = redis_store.get('facility_list')

    if not facility_list:
        try:
            facilitys = Facility.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DATAERR, msg=ret_map[RET.DATAERR])

        facility_list = [facility.to_dict() for facility in facilitys]

        redis_store.set('facility_list', json.dumps(facility_list))
    else:
        facility_list = json.loads(facility_list)
    return facility_list

@house_blueprint.route('/house/area_facility')
def area_facility():
    #查询地区
    areas_list = area_get()

    #查询房屋配置
    facilitys_list = facility_get()


    return jsonify(area=areas_list,facility=facilitys_list)


@house_blueprint.route('/house/index')
def house_index():
    alist = area_get()

    return jsonify(code=RET.OK,msg=ret_map[RET.OK], alist=alist)